package cn.cl.gulimall.product.service.impl;

import cn.cl.gulimall.product.dao.AttrAttrgroupRelationDao;
import cn.cl.gulimall.product.dao.AttrGroupDao;
import cn.cl.gulimall.product.dao.CategoryDao;
import cn.cl.gulimall.product.entity.AttrAttrgroupRelationEntity;
import cn.cl.gulimall.product.entity.AttrGroupEntity;
import cn.cl.gulimall.product.entity.CategoryEntity;
import cn.cl.gulimall.product.service.CategoryService;
import cn.cl.gulimall.product.vo.AttrGroupRelationVo;
import cn.cl.gulimall.product.vo.AttrRespVo;
import cn.cl.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cl.common.utils.PageUtils;
import cn.cl.common.utils.Query;

import cn.cl.gulimall.product.dao.AttrDao;
import cn.cl.gulimall.product.entity.AttrEntity;
import cn.cl.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.management.relation.Relation;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
	@Autowired
	private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
	@Autowired
	private AttrGroupDao attrGroupDao;
	@Autowired
	private CategoryDao categoryDao;
	@Autowired
	private CategoryService categoryService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<AttrEntity> page = this.page(
				new Query<AttrEntity>().getPage(params),
				new QueryWrapper<AttrEntity>()
		);

		return new PageUtils(page);
	}

	/**
	 * 保存
	 */
	@Transactional
	@Override
	public void saveAttr(AttrVo attr) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attr, attrEntity);
		// 1、保存基本数据
		this.save(attrEntity);
		// 2、保存关联关系
		if (attr.getAttrType() == 1) {
			AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
			attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
			attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
			attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
		}
	}

	/**
	 * 查询
	 */
	@Override
	public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
		QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);
		if (catelogId != 0) {
			queryWrapper.eq("catelog_id", catelogId);
		}
		String key = (String) params.get("key");
		if (!StringUtils.isEmpty(key)) {
			queryWrapper.and((obj) -> {
				obj
						.eq("attr_id", key)
						.or()
						.like("attr_name", key);
			});
		}
		IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
		PageUtils pageUtils = new PageUtils(page);
		List<AttrEntity> records = page.getRecords();
		List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
			AttrRespVo attrRespVo = new AttrRespVo();
			BeanUtils.copyProperties(attrEntity, attrRespVo);
			// 设置分类和分组的名字
			if ("base".equalsIgnoreCase(attrType)) {
				AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
				if (attrAttrgroupRelationEntity != null) {
					AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
					if (attrGroupEntity != null) {
						attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
					}
				}
			}
			CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
			if (categoryEntity != null) {
				attrRespVo.setCatelogName(categoryEntity.getName());
			}
			return attrRespVo;
		}).collect(Collectors.toList());
		pageUtils.setList(attrRespVos);
		return pageUtils;
	}

	/**
	 * 查询单个信息
	 */
	@Override
	public AttrRespVo getAttrInfo(Long attrId) {
		AttrEntity attrEntity = this.getById(attrId);
		AttrRespVo attrRespVo = new AttrRespVo();
		BeanUtils.copyProperties(attrEntity, attrRespVo);
		// 1、设置分组信息
		AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
		if (attrAttrgroupRelationEntity != null) {
			attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
			AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
			if (attrGroupEntity != null) {
				attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
			}
		}
		// 2、设置分类信息
		Long catelogId = attrEntity.getCatelogId();
		Long[] path = categoryService.findCatelogPath(catelogId);
		attrRespVo.setCatelogPath(path);
		CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
		if (categoryEntity != null) {
			attrRespVo.setCatelogName(categoryEntity.getName());
		}
		return attrRespVo;
	}

	/**
	 * 修改
	 */
	@Transactional
	@Override
	public void updateAttr(AttrVo attr) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attr, attrEntity);
		this.updateById(attrEntity);
		if (attr.getAttrType() == 1) {
			// 修改分组关联
			AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
			attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
			attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
			Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
			if (count > 0) {
				attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
			} else {
				attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
			}
		}
	}

	/**
	 * 根据分组ID找到改分组关联的所有属性
	 */
	@Override
	public List<AttrEntity> getRelationAttr(Long attrgroupId) {
		List<AttrAttrgroupRelationEntity> entityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
		if (entityList == null) {
			return null;
		}
		List<Long> attrIds = entityList.stream().map((attr) -> {
			return attr.getAttrId();
		}).collect(Collectors.toList());
		if (attrIds == null || attrIds.size() <= 0) {
			return null;
		}
		List<AttrEntity> entities = this.listByIds(attrIds);
		return entities;
	}

	/**
	 * 删除属性分组和属性的关联关系
	 */
	@Override
	public void deleteRelation(AttrGroupRelationVo[] vos) {
		// attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", 1L ).eq("attr_group_id", 1L));
		List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList = Arrays.asList(vos).stream().map((item) -> {
			AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
			BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
			return attrAttrgroupRelationEntity;
		}).collect(Collectors.toList());
		attrAttrgroupRelationDao.deleteBatchRelation(attrAttrgroupRelationEntityList);
	}

	/**
	 * 获取当前属性分组没有关联的属性
	 *
	 * @param params
	 * @param attrgroupId
	 */
	@Override
	public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
		// 1、当前分组只能关联自己所属分类里面的所有属性
		AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
		Long catelogId = attrGroupEntity.getCatelogId();
		// 2、 当前分组只能关联别的分组没有引用的属性
		// 2.1、当前分类下的其他分组
		List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
		List<Long> attrgroupIds = attrGroupEntities.stream().map((item) -> {
			return item.getAttrGroupId();
		}).collect(Collectors.toList());
		// 2.2、这些分组关联的属性
		QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
		queryWrapper.eq("attr_type", 1);
		if (attrgroupIds != null && attrgroupIds.size() > 0) {
			List<AttrAttrgroupRelationEntity> AttrAttrgroupRelationEntitys = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrgroupIds));
			List<Long> attrIds = AttrAttrgroupRelationEntitys.stream().map((item) -> {
				return item.getAttrId();
			}).collect(Collectors.toList());
			if (attrIds != null && attrIds.size() > 0) {
				// 2.3、从当前分类的所有属性中剔除这些属性
				queryWrapper.eq("catelog_id", catelogId).notIn("attr_id", attrIds);
			}
			String key = (String) params.get("key");
			if (!StringUtils.isEmpty(key)) {
				queryWrapper.and((w) -> {
					w.eq("attr_id", key).or().like("attr_name", key);
				});
			}
		}
		IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
		return new PageUtils(page);
	}
}